package cn.qiguai.sphapi.controller;

import cn.qiguai.sphapi.controller.request.CommitPayOrderParam;
import cn.qiguai.sphapi.controller.request.GetPageOrderParam;
import cn.qiguai.sphapi.controller.response.Status;
import cn.qiguai.sphapi.controller.response.Result;
import cn.qiguai.sphapi.service.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Positive;
import java.util.Optional;

@RestController
@RequestMapping("/api/payOrder")
@Validated
public class PayOrderController {
	@Autowired
	private PayOrderService payOrderService;

	@PostMapping("/commitPayOrder")
	public Result commitPayOrder(@RequestBody @Validated CommitPayOrderParam param) {
		return payOrderService.commitPayOrder(param) ? new Result(Status.COMMIT_ORDER_OK, param) : new Result(Status.COMMIT_ORDER_ERR);
	}

	@GetMapping("/pay/{orderId}")
	public Result pay(@PathVariable @Positive int orderId) {
		return payOrderService.pay(orderId) ? new Result(Status.PAY_OK) : new Result(Status.PAY_ERR);
	}

	@PostMapping("/getPagePayOrder")
	public Result getPagePayOrder(@RequestBody @Validated GetPageOrderParam param) {
		return Optional
				.of(payOrderService.getPagePayOrder(param))
				.map(page -> Result
						.builder()
						.code(Status.SELECT_OK.getCode())
						.msg(Status.SELECT_OK.getMsg())
						.data(page)
						.build())
				.orElse(Result.builder().build());
	}

	@GetMapping("/getPayOrderStatus/{orderId}")
	public Result getPayOrderStatus(@PathVariable @Positive int orderId) {
		return Optional
				.of(payOrderService.getPayOrderStatus(orderId))
				.map(status -> Result
						.builder()
						.code(Status.SELECT_OK.getCode())
						.msg(Status.SELECT_OK.getMsg())
						.data(status)
						.build())
				.orElse(Result.builder().build());
	}
}
